package com.spzhao.qrcodescaner;

import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Toast;

import com.baoyz.swipemenulistview.SwipeMenu;
import com.baoyz.swipemenulistview.SwipeMenuAdapter;
import com.baoyz.swipemenulistview.SwipeMenuCreator;
import com.baoyz.swipemenulistview.SwipeMenuItem;
import com.baoyz.swipemenulistview.SwipeMenuListView;
import com.google.android.gms.appindexing.Action;
import com.google.android.gms.appindexing.Thing;
import com.google.zxing.integration.android.IntentIntegrator;
import com.google.zxing.integration.android.IntentResult;

import org.json.JSONException;
import org.json.JSONObject;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import adapters.QrCodeMessageAdapter;
import beans.QrMessage;
import config.AppConfig;
import interfaces.MyCallBack;
import utils.SharePHelper;

public class MainActivity extends AppCompatActivity implements View.OnClickListener {

    private final static String TAG = "MainActivity LOG";
    private SharePHelper sharePHelper;
    private SwipeMenuListView swipeMenuListView;
    private SwipeMenuCreator sCreator;
    private SwipeMenuAdapter adapter;
    private QrCodeMessageAdapter qrCodeMessageAdapter;
    private ArrayList<QrMessage> qrMessages;
    private SwipeRefreshLayout refreshLayout;
    /**
     * ATTENTION: This was auto-generated to implement the App Indexing API.
     * See https://g.co/AppIndexing/AndroidStudio for more information.
     */
//    private GoogleApiClient client;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
        fab.setOnClickListener(this);

        initSPData();
        bindViews();
        initRefreshLayout();
        stopRefresh();

        // ATTENTION: This was auto-generated to implement the App Indexing API.
        // See https://g.co/AppIndexing/AndroidStudio for more information.
//        client = new GoogleApiClient.Builder(this).addApi(AppIndex.API).build();
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    /**
     * 初始化布局和控件；设置列表数据；
     * item点击事件；
     * listView配置
     */
    private void bindViews() {
        swipeMenuListView = (SwipeMenuListView) this.findViewById(R.id.QListView);
        qrCodeMessageAdapter = new QrCodeMessageAdapter(this, qrMessages);
//        adapter = new SwipeMenuAdapter(this,qrCodeMessageAdapter);
        swipeMenuListView.setAdapter(qrCodeMessageAdapter);
        sCreator = new SwipeMenuCreator() {
            @Override
            public void create(SwipeMenu menu) {
                SwipeMenuItem copyItem = new SwipeMenuItem(MainActivity.this);
                copyItem.setBackground(R.color.copyBackgroundColor);
                copyItem.setWidth(200);
                copyItem.setIcon(R.drawable.copy);
                menu.addMenuItem(copyItem);

                SwipeMenuItem deleteItem = new SwipeMenuItem(MainActivity.this);
                deleteItem.setBackground(R.color.colorDelete);
                deleteItem.setWidth(200);
                deleteItem.setIcon(android.R.drawable.ic_menu_delete);
                menu.addMenuItem(deleteItem);
            }
        };
        swipeMenuListView.setMenuCreator(sCreator);
        swipeMenuListView.setOnMenuItemClickListener(new SwipeMenuListView.OnMenuItemClickListener() {
            @Override
            public boolean onMenuItemClick(int position, SwipeMenu menu, int index) {
                switch (index) {
                    case 1:
                        Log.d(TAG, "delete" + Integer.toString(position));
                        // 从sp中移除该数据
                        sharePHelper.getInstance(AppConfig.QRCODE_SHAREP_NAME).
                                edit().remove(qrCodeMessageAdapter.getItem(position).getName()).apply();
                        // 从列表中移除该数据
                        qrCodeMessageAdapter.removeItem(position);
                        break;
                    default:
                        qrCodeMessageAdapter.getItem(position).copyToClip();
                        break;
                }
                return true;
            }
        });
        // 设置为向左滑
        swipeMenuListView.setSwipeDirection(SwipeMenuListView.DIRECTION_LEFT);
        // item点击事件绑定
        swipeMenuListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                QrMessage q = qrCodeMessageAdapter.getItem(i);
                JSONObject json = new JSONObject();
                try {
                    json.put("text", q.getText());
                    json.put("name", q.getName());
                    json.put("time", q.getCreateTime());
                    json.put("color", q.getColor());
                    json.put("code", i);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                goDetail(json.toString(), i);
            }
        });
//        swipeMenuListView
    }

    private void updateList(ArrayList<QrMessage> datas) {
        qrCodeMessageAdapter.setData(datas);
    }

    /**
     * 刷新会跟自定义列表有冲突，会影响侧滑效果
     */
    private void initRefreshLayout() {
        if (refreshLayout == null) {
            refreshLayout = (SwipeRefreshLayout) findViewById(R.id.qrListRefresh);
        }
        refreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
//                try {
//                    initSPData();
//                    updateList(qrMessages);
//                } catch (Exception e) {
//                    e.printStackTrace();
//                } finally {
//                    stopRefresh();
//                }
            }
        });
    }

    private void stopRefresh() {
        if (refreshLayout != null) {
            refreshLayout.setRefreshing(false);
        }
    }

    /**
     * 初始化和格式化数据，从sharedPreference中获取多有数据，添加到对象数组中
     */
    private void initSPData() {
        if (sharePHelper == null) {
            sharePHelper = new SharePHelper(this);
        }
        SharedPreferences msp = sharePHelper.getInstance(AppConfig.QRCODE_SHAREP_NAME);

        Map<String, ?> maps = new HashMap<>();

        maps = msp.getAll();

        JSONObject json = new JSONObject();

        qrMessages = new ArrayList<QrMessage>();

        for (Map.Entry<String, ?> entry : maps.entrySet()) {
//            Log.i(TAG, "key: " + entry.getKey());
//            Log.i(TAG, "value: " + entry.getValue().toString());
            try {
                json = new JSONObject(entry.getValue().toString());
                qrMessages.add(new QrMessage(
                        json.getString("name"),
                        json.getString("text"),
                        json.getString("time"),
                        json.getString("color")
                ));
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    @Override
    public void onClick(View view) {
        // 打开扫描
//        Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_SHORT)
//                .setAction("Action", null).show();
        IntentIntegrator integrator = new IntentIntegrator(this);
        integrator.setPrompt("请扫描");
        integrator.setCaptureActivity(ScanActivity.class);
        integrator.initiateScan();
    }

    /**
     * 保存到SP；如果已存在则不保存
     *
     * @param key  键值
     * @param json json格式的数据
     */
    private void saveToSp(String key, JSONObject json) {
        if (json == null) {
            return;
        }
        if (sharePHelper == null) {
            sharePHelper = new SharePHelper(this);
        }
        // 当前的值未存在
        if ("".equals(sharePHelper.getValue(key, AppConfig.QRCODE_SHAREP_NAME))) {
            sharePHelper.push(key, json.toString(), AppConfig.QRCODE_SHAREP_NAME, new MyCallBack() {
                @Override
                public void callback() {
                }
            });
        }
    }

    /**
     * 格式化数据；如果sp中未存在该数据，那么就在listView中添加该数据
     * 存储的字段包含 name，text,time,color
     *
     * @param data 拍照回去的数据
     * @return json对象
     */
    private JSONObject initQrCodeData(String data) {
        JSONObject tmp = new JSONObject();
        try {
            tmp.put("text", data);

            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String time = sdf.format(new Date());
            Log.i(TAG, time);
            tmp.put("time", time);
            tmp.put("color", AppConfig.DEFAULT_COLOR);
            tmp.put("name", data);
            Log.i(TAG, "data " + sharePHelper.getValue(data));
            if ("".equals(sharePHelper.getValue(data, AppConfig.QRCODE_SHAREP_NAME))) {
                qrCodeMessageAdapter.addItem(new QrMessage(
                        data,
                        data,
                        time,
                        AppConfig.DEFAULT_COLOR
                ));
            } else {
                return null;
            }
            return tmp;
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 获取返回信息
     * @param requestCode 请求状态码
     * @param resultCode 结果状态码
     * @param data 返回数据
     */
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        IntentResult result = IntentIntegrator.parseActivityResult(requestCode, resultCode, data);
        Log.i(TAG, "result code" + Integer.toString(resultCode));
        /**
         * 拍照返回处理
         */
        if (result != null) {
            if (result.getContents() != null) {
                Toast.makeText(this, result.getContents().toString(), Toast.LENGTH_SHORT).show();
                saveToSp(result.getContents().toString(), initQrCodeData(result.getContents().toString()));
            } else {
                Toast.makeText(this, "fail or cancel", Toast.LENGTH_SHORT).show();
            }
        } else {
            Log.i(TAG,"result is null");
            super.onActivityResult(requestCode, resultCode, data);
        }
        /**
         * 二维码编辑返回信息
         * <p>刷新数据</p>
         */
        if (data != null) {
            if (requestCode >= 0) {
                initSPData();
                updateList(qrMessages);
            }
        }
    }

    private void goDetail(String data, int code) {
        Intent intent = new Intent();
        intent.setClass(MainActivity.this, QrCode_detail.class);
        intent.putExtra("data", data);
        startActivityForResult(intent, code);
    }

    /**
     * ATTENTION: This was auto-generated to implement the App Indexing API.
     * See https://g.co/AppIndexing/AndroidStudio for more information.
     */
    public Action getIndexApiAction() {
        Thing object = new Thing.Builder()
                .setName("Main Page") // TODO: Define a title for the content shown.
                // TODO: Make sure this auto-generated URL is correct.
                .setUrl(Uri.parse("http://[ENTER-YOUR-URL-HERE]"))
                .build();
        return new Action.Builder(Action.TYPE_VIEW)
                .setObject(object)
                .setActionStatus(Action.STATUS_TYPE_COMPLETED)
                .build();
    }

    @Override
    public void onStart() {
        super.onStart();

        // ATTENTION: This was auto-generated to implement the App Indexing API.
        // See https://g.co/AppIndexing/AndroidStudio for more information.
//        client.connect();
//        AppIndex.AppIndexApi.start(client, getIndexApiAction());
    }
}
